package com.budwk.app.sqfw.controllers.admin;

import cn.hutool.core.bean.BeanUtil;
import com.budwk.app.sqfw.dto.DynamicFormConfSaveDTO;
import com.budwk.app.sqfw.models.DynamicFormConf;
import com.budwk.app.sqfw.services.DynamicFormConfService;
import com.budwk.starter.common.openapi.annotation.ApiDefinition;
import com.budwk.starter.common.openapi.annotation.ApiOperation;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.*;

import java.util.Date;

/**
 * @author ZY.Wang
 * @since 2024/6/11
 */
@IocBean
@At("platform/assistance/dynamicFormConf")
@ApiDefinition(tag = "社区助手动态表单配置存储")
@Slf4j
public class DynamicFormConfController {

    @Inject
    private DynamicFormConfService dynamicFormConfService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "更新动态表单配置")
    public Result<?> updateConfig(@Param("config") DynamicFormConfSaveDTO saveDTO) {
        String userId = SecurityUtil.getUserId();

        if (StringUtils.isBlank(saveDTO.getType())) return Result.error();

        Cnd cnd = Cnd.NEW().and(DynamicFormConf::getType, "=", saveDTO.getType());
        DynamicFormConf dynamicFormConf = dynamicFormConfService.fetch(cnd);

        if (dynamicFormConf == null) {
            DynamicFormConf conf = new DynamicFormConf();
            BeanUtil.copyProperties(saveDTO, conf);
            conf.setCreateDate(new Date());
            conf.setCreatedBy(userId);
            conf.setUpdatedBy(userId);
            dynamicFormConfService.insert(conf);
        } else {
            dynamicFormConf.setUpdatedBy(userId);
            dynamicFormConf.setUpdateDate(new Date());
            dynamicFormConf.setConf(saveDTO.getConf());
            dynamicFormConfService.update(dynamicFormConf);
        }
        return Result.success();
    }

    @At
    @Ok("json")
    @GET
    @ApiOperation(name = "获取动态表单配置")
    public Result<?> getConfig(@Param("type") String type) {
        if (StringUtils.isBlank(type)) return Result.error();
        Cnd cnd = Cnd.NEW();
        cnd.and(DynamicFormConf::getType, "=", type);
        DynamicFormConf conf = dynamicFormConfService.fetch(cnd);
        if (conf == null) return Result.success();
        return Result.data(conf);
    }

}
